import {
  timestampToDate
} from '../../utils/time.js'
Page({
  data: {
    detail: {}
  },
  onLoad(opt) {
    wx.cloud.database().collection('news')
      .doc(opt.id)
      .get()
      .then(res => {
        res.data.time = timestampToDate(res.data.time)
        this.turnImageUrl(res.data.content)
        this.setData({
          detail: res.data
        })
      })
      .catch(res => {
        console.log("新闻请求失败", res)
      })
    wx.cloud.database().collection('collect')
      .where({
        newId: opt.id
      })
      .get().then(res => {
        if (res.data && res.data.length > 0) {
          this.setData({
            isCollect: true
          })
        }
      }).catch(res => {
        console.log(res)
      })
  },
  turnImageUrl(content) {
    var index = content.indexOf("cloud:")
    if (index == -1)
      return;
    var styleIndex = content.indexOf("width", index)
    var styleEndIndex = content.indexOf(">", styleIndex)
    var endIndex = content.indexOf(".jpg", index) + 4
    var src = content.substring(index, endIndex)
    var styleSrc = content.substring(styleIndex, styleEndIndex)
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID: src
      }]
    }).then(res => {
      content = content.replace(src, res.fileList[0].tempFileURL)
      content = content.replace(styleSrc,
        "style=\"width:100%;height:auto;\"")
      this.setData({
        "detail.content": content
      })
      this.turnImageUrl(content)
    })
  },
  collect() {
    var detail = this.data.detail
    wx.cloud.database().collection('collect')
      .add({
        data: {
          newId: detail._id,
          title: detail.title,
          imgs: detail.imgs
        }
      }).then(res => {
        console.log(res)
        this.setData({
          isCollect: true
        })
        wx.showToast({
          title: '收藏成功',
        })
      }).catch(res => {
        console.log(res)
      })
  },
  collect_no() {
    wx.cloud.database().collection('collect')
      .where({
        newId: this.data.detail._id
      }).remove()
      .then(res => {
        console.log(res)
        this.setData({
          isCollect: false
        })
        wx.showToast({
          title: '取消收藏成功',
        })
      }).catch(res => {
        console.log(res)
      })
  },
  enlarge(e) {
    var index = e.currentTarget.dataset.idx
    var url = this.data.detail.imgs[index]
    wx.previewImage({
      current: url,
      urls: this.data.detail.imgs
    })
  }
})